********************************************************************************
* Binance for several perpetuals
*   Available at https://www.binance.com/en/futures/funding-history/perpetual/funding-fee-history
********************************************************************************

local filenames: dir "build/input/binance/" files "*7-10_pseudo.csv"
di `filenames'

tempfile binance

foreach f of local filenames {
	di "`f'"
	
	import delimited "build/input/binance/`f'", delimiter(comma) varnames(1)  clear 

	replace fundingrate = subinstr(fundingrate, "%", "",.) 
	destring fundingrate, replace
	
	gen apr = fundingrate * 3 * 365 // percent, 3 payments per day (every 8 hours); 

	
	// daily rate = funding rate (0.01%) * 3
	// annual rate = funding rate (0.01%) * 3 * 365
	
	gen double eventtime = clock(time, "YMDhms")
	format eventtime %tc
	gen date = dofc(eventtime)
	format date %td

	tsset eventtime
	
	gen hour = hh(eventtime)

	sort eventtime
	
	capture confirm file "`binance'"
	if _rc==0 {
		append using "`binance'"
		save "`binance'", replace
	}
	else {
		save "`binance'", replace
	}

}


use `binance', clear

gen base = ""
replace base = "USDT" if strpos(contracts, "USDT")>0
replace base = "BUSD" if strpos(contracts, "BUSD")>0

gen coin = contracts
replace coin = subinstr(coin, "USDT", "",.)
replace coin = subinstr(coin, "BUSD", "",.)
replace coin = subinstr(coin, "Perpetual", "",.)
replace coin = subinstr(coin, " ","",.)

drop contracts
gen pair = coin+base

collapse (mean) apr (last) coin base, by(date pair)
drop pair

gen exchange = "Binance"

sort exchange date coin
rename apr funding_apr

save "build/output/futures_funding_long.dta", replace

********************************************************************************
* Main variable: Binance BTC/USDT
********************************************************************************

duplicates drop
keep if base == "USDT"
keep if exchange == "Binance"
keep if coin == "BTC"
save "build/output/futures_funding_avg.dta", replace
